package com.nengchuan.eic.nceconomy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nengchuan.eic.nceconomy.constant.CommonConstant;
import com.nengchuan.eic.nceconomy.dao.ExcelFileMapper;
import com.nengchuan.eic.nceconomy.dao.ExcelVerifyMapper;
import com.nengchuan.eic.nceconomy.dao.OriginIndexDataMapper;
import com.nengchuan.eic.nceconomy.entity.dto.ExcelDetailDTO;
import com.nengchuan.eic.nceconomy.entity.dto.ExcelUploadDTO;
import com.nengchuan.eic.nceconomy.entity.dto.VerifyConfirmDTO;
import com.nengchuan.eic.nceconomy.entity.po.ExcelFile;
import com.nengchuan.eic.nceconomy.entity.po.ExcelVerify;
import com.nengchuan.eic.nceconomy.entity.po.VerifyResult;
import com.nengchuan.eic.nceconomy.dao.VerifyResultMapper;
import com.nengchuan.eic.nceconomy.entity.vo.VerifyResultVO;
import com.nengchuan.eic.nceconomy.service.VerifyResultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nengchuan.util.NullCheckUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 校验结果表 服务实现类
 * </p>
 *
 * @author luoping
 * @since 2020-04-23
 */
@Service
public class VerifyResultServiceImpl extends ServiceImpl<VerifyResultMapper, VerifyResult> implements VerifyResultService {

    @Autowired
    private VerifyResultMapper verifyResultMapper;

    @Autowired
    private ExcelVerifyMapper excelVerifyMapper;

    @Autowired
    private ExcelFileMapper excelFileMapper;

    @Autowired
    private OriginIndexDataMapper originIndexDataMapper;

    @Autowired
    private ExcelVerifyService excelVerifyService;

    @Transactional(rollbackFor = Exception.class)
    public int insert(VerifyResult verifyResult) {
        return verifyResultMapper.insert(verifyResult);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertList(ExcelVerify excelVerify, List<VerifyResult> verifyResults) {
        //删除历史校验数据
        LambdaQueryWrapper<ExcelVerify> excelVerifyQueryWrapper=new QueryWrapper<ExcelVerify>().lambda()
                .eq(ExcelVerify::getPid,excelVerify.getPid())
                .eq(ExcelVerify::getCategoryIndex,excelVerify.getCategoryIndex())
                .eq(ExcelVerify::getProjectIndex,excelVerify.getProjectIndex())
                .eq(ExcelVerify::getVersion,excelVerify.getVersion());
        if(excelVerify.getProjectId()==null){
            excelVerifyQueryWrapper.isNull(ExcelVerify::getProjectId);
        }else{
            excelVerifyQueryWrapper.eq(ExcelVerify::getProjectId,excelVerify.getProjectId());
        }
        excelVerifyService.remove(excelVerifyQueryWrapper);

        if(!excelVerifyService.save(excelVerify)){
            return 0;
        }

        if (NullCheckUtils.isNull(verifyResults)) {
            return 0;
        }

        LambdaQueryWrapper<VerifyResult> verifyResultQueryWrapper=new QueryWrapper<VerifyResult>().lambda().eq(VerifyResult::getExcelVerifyId,excelVerify.getId());
        verifyResultMapper.delete(verifyResultQueryWrapper);

        verifyResults.forEach(e->e.setExcelVerifyId(excelVerify.getId()));

        return verifyResultMapper.insertList(verifyResults);
    }

    /**
     * 查询验证结果
     *
     * @param dto
     * @return
     */
    @Override
    public VerifyResultVO getVerifyResult(ExcelUploadDTO dto) {
        VerifyResultVO verifyResultVO = new VerifyResultVO();
        List<VerifyResultVO.Result> sheetResult = new ArrayList<>();
        //用户是否已确认
        ExcelVerify excelVerify=verifyResultMapper.getVerifyIsConfirm(dto);
        if(excelVerify==null){
            verifyResultVO.setIsPass(true);
            return verifyResultVO;
        }
        List<VerifyResult> results = verifyResultMapper.getVerifyResult(dto);
        List<VerifyResult> collect = results.stream().filter(x -> CommonConstant.verifyResult.CHECK_TYPE_SHEET == x.getCheckType()).collect(Collectors.toList());
        collect.forEach(x -> {
            sheetResult.add(new VerifyResultVO.Result(x.getId(), x.getTemplateSheetName(), x.getSheetName(), x.getStatus()));
        });
        verifyResultVO.setSheetResult(sheetResult);
        long count = results.stream().filter(x -> CommonConstant.verifyResult.CHECK_TYPE_CONTENT == x.getCheckType()).filter(x -> CommonConstant.verifyResult.STATUS_PASS != x.getStatus()).count();
        verifyResultVO.setContentDiffNum(count);
        //是否有错误
        long count1 = sheetResult.stream().filter(x -> CommonConstant.verifyResult.STATUS_PASS != x.getStatus()).count();
        if (count1 ==0&&(excelVerify.getConfirmFlag()==CommonConstant.verifyConfirm.CONFIRM||count==0)) {
            verifyResultVO.setIsPass(true);
        } else {
            verifyResultVO.setIsPass(false);
        }
        if(CollectionUtils.isNotEmpty(results)){
            verifyResultVO.setExcelName(results.get(0).getExcelName());
        }
        return verifyResultVO;
    }

    /**
     * 确认结果
     *
     * @param dto
     * @return
     */
    @Override
    public String getConfirmResult(VerifyConfirmDTO dto) {
        ExcelDetailDTO firstSheet = excelFileMapper.getFirstSheet(dto.getPid(), dto.getProjectId(), dto.getCategoryCode(), dto.getProjectCode(), dto.getVersion().toString());
        List<VerifyResult> results = verifyResultMapper.selectBatchIds(dto.getVerifyId());
        if(CollectionUtils.isNotEmpty(results)){
            if(results.get(0).getCheckType()==CommonConstant.verifyResult.CHECK_TYPE_CONTENT){
                ExcelVerify excelVerify = excelVerifyMapper.getById(results.get(0).getExcelVerifyId());
                excelVerify.setConfirmFlag(CommonConstant.verifyConfirm.CONFIRM);
                excelVerifyMapper.updateById(excelVerify);
            }

            results.forEach(x->{
                x.setStatus(CommonConstant.verifyResult.STATUS_PASS);
                verifyResultMapper.updateById(x);
                if(x.getCheckType()==CommonConstant.verifyResult.CHECK_TYPE_CONTENT){
                    originIndexDataMapper.updateConfirmData(firstSheet.getSheetId(),x.getLineNum());
                }
            });

        }

        return "成功";
    }

    /**
     * 在线预览-内容校验
     *
     * @param dto
     * @return
     */
    @Override
    public List<VerifyResultVO.ContentResult> getOnlineView(ExcelUploadDTO dto) {
        List<VerifyResultVO.ContentResult> sheetResult = new ArrayList<>();
        List<VerifyResult> results = verifyResultMapper.getVerifyResult(dto);
        List<VerifyResult> collect = results.stream().filter(x -> CommonConstant.verifyResult.CHECK_TYPE_CONTENT == x.getCheckType()).collect(Collectors.toList());
        collect.forEach(x -> {
            sheetResult.add(new VerifyResultVO.ContentResult(x.getId(), x.getTemplateSheetName(), x.getSheetName(), x.getTemplateSerialNum(),x.getTemplateVal(),x.getExcelSerialNum(),x.getExcelVal(),x.getStatus(),x.getErrorMsg()));
        });
        return sheetResult;
    }

}
